//
//  BJHomeViewController.m
//  BowJoy
//
//  Created by  on 2024/5/13.
//

#import "BJHomeViewController.h"
#import "BJRewardPopView.h"
#import "BJRewardAginPopView.h"
#import "BJAnchorManager.h"
#import "BJFMDBManager.h"
#import "BJArticleViewController.h"
#import "BJArticleInfoViewController.h"
@interface BJHomeViewController ()

@property (weak, nonatomic) IBOutlet UIView *scrollViewBgView;

@property (nonatomic)UIScrollView *scrollView;
@property (nonatomic)UIScrollView *anchorListScrollView;

@property (weak, nonatomic) IBOutlet UIView *anchorListBgView;

@property(nonatomic)BJAnchorWallModel *viewModel;

@property(nonatomic) NSArray *titileArr;
@property(nonatomic) NSArray *contentArr;
@property(nonatomic) NSArray *imageArr;
@property(nonatomic) NSMutableArray *dataList;
@property(nonatomic) UIImageView *selectIcon1;
@property(nonatomic) UIImageView *selectIcon2;
@property(nonatomic) UIImageView *selectIcon3;
@property(nonatomic) UIImageView *selectIcon4;
@property(nonatomic) NSInteger checkNum;

@end

@implementation BJHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.dataList = [[NSMutableArray alloc]init];
    [[BJFMDBManager sharedManager] creatDatabase];
    [[BJPushFMDBManger sharedManager] creatDatabase];
    [[BJFMDBVoiceManager sharedManager] creatDatabase];
    [[BJFMDBCommentManager sharedManager] creatDatabase];
    [[BJFMDBBlockManager sharedManager] creatDatabase];

    
    self.titileArr = @[@"🎯 Bullseye Chronicles: My Archery Journey!",
                       @"🌟 Shooting for Success: Archery Adventures!",
                       @"� Arrow's Path: Precision in Life!",
                       @"🔥 Flaming Arrows: Igniting Passion!",
                       @"🌌 Aiming True: Purposeful Shots!",
                       @"🌈 Rainbow Arrows: Dream Flight!",
                       @"🔥 Inferno of Skill: Goals Ablaze!",
                       @"⚡ Thunderous Shots: Achieving Lightning!",
                       @"🌌 Cosmic Archery: Shooting Beyond Stars!",
                       @"🎯 Piercing Challenges: Resilient Arrows!",
                       @"🌒 Eclipsing Limits: Beyond Shooting!",
                       @"🌙 Guided by Stars: Night Sky Adventures!",
                       @"💥 Explosive Precision: Ambitious Arrows!",
                       @"🌈 Rainbow Targets: Victorious Shots!",
                       @"🏅 Breaking Records: Archery History!",
                       @"✨ Arcane Archery: Spells of Precision!",
                       @"🌠 Steady Aim: Constellations of Success!",
                       @"🛤 Blazing Trails: Archery Excellence!",
    
    ];
    self.contentArr = @[
        @"Sharing my archery journey, hitting targets with precision and passion! 🎯",
        @"With rainbow arrows, dreams take flight, painting the sky with aspirations! 🌈",
        @"Inferno of skill ignites my goals, setting them ablaze with precision! 🔥",
        @"Thunderous shots of achievement reverberate through the archery range! ⚡",
        @"Every shot counts in my pursuit of success; archery adventures unfold! 🌟",
        @"Shooting for cosmic dreams and beyond; the universe awaits my aim! 🌌",
        @"Piercing through adversities with resilient arrows; challenges overcome! 🎯",
        @"Eclipsing the boundaries, shooting beyond limits to achieve greatness! 🌒",
        @"Under the night sky, guided by stars, I embark on archery adventures! 🌙",
        @"Explosive ambition fuels my precision; every arrow a testament to my drive! 💥",
        @"Blazing trails of excellence on the archery range; forging my own path! 🛤",
        @"Navigating life's twists and turns with arrow-like precision and focus! 💫",
        @"Each arrow aimed with purpose, shooting true towards a meaningful life! 🌌",
        @"Steady aim guiding me through the constellation of success; reaching for stars! 🌠",
        @"Delving into the arcane art of archery, mastering precision and power! ✨",
        @"Breaking records one precise shot at a time, etching my name in history!🏅",
        @"Vibrant victories painted across the archery range; aiming for the rainbow! 🌈",
        @"Fueling my archery passion with the fiery intensity of every shot released! 🔥",
    ];
    self.imageArr = @[
        @[@"a_1001",@"a_1002",@"a_2001"],
        @[@"b_1001",@"b_1002",@"b_2001"],
        @[@"c_1001",@"c_1002"],
        @[@"d_1001",@"d_1002",@"d_2001"],
        @[@"e_1001",@"e_1002"],
        @[@"f_1001",@"f_1002",@"f_1003"],
        @[@"g_1001",@"g_1002"],
        @[@"h_1001",@"h_1002",@"h_2001"],
        @[@"i_1001",@"i_1002",@"i_2001"],
        @[@"j_1001",@"j_1002"],
        @[@"k_1001",@"k_1002"],
        @[@"l_1001",@"l_1002"],
    ];

    [self initArrowView];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    NSMutableArray *dataList = [NSMutableArray array];
    NSDictionary *dict = @{
        @"page":@"home",
        @"duration":@(0),
        @"event":@"pv",
        @"tm":@([[BJNetManager shareNetManager] gs_getCurrentTimeToMilliSecond]),
    };
    [dataList addObject:dict];
    [[BJNetManager shareNetManager]postLogWithParam:dataList];
    
    [self getData];
}


- (void)initUI{
    
    self.anchorListScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, kScreenW, kScreenH)];
    self.anchorListScrollView.contentSize = CGSizeMake(150*4, 170);
    self.anchorListScrollView.directionalLockEnabled = YES;
    [self.anchorListBgView addSubview:self.anchorListScrollView];

    kWeakSelf(weakSelf)
    for (int i = 0; i<self.dataList.count; i++) {
        if (i>3) {
            return;
        }
        BJAnchorWallModelData *model = self.dataList[i];
        UIView *view = [[UIView alloc]init];
        [self.anchorListScrollView addSubview:view];
        view.makeCons(^{
            make.left.constants(150*i);
            make.width.constants(140);
            make.height.constants(170);
            make.top.constants(0);
        });
        view.onClick(^{
            BJArticleInfoViewController *vc = [[BJArticleInfoViewController alloc] init];
            vc.model = model;
            [weakSelf.navigationController pushViewController:vc animated:YES];
        });
        
        NSArray *imageArr = [model.imageArrStr componentsSeparatedByString:@","];
        UIImageView *imageView = [[UIImageView alloc] init];
        imageView.image = [UIImage imageNamed:imageArr[0]];
        imageView.layer.masksToBounds = YES;
        imageView.layer.cornerRadius = 12;
        imageView.contentMode = UIViewContentModeScaleAspectFill;
        [view addSubview:imageView];
        imageView.makeCons(^{
            make.left.constants(10);
            make.width.constants(133);
            make.height.constants(128);
            make.top.constants(0);
        });
        
        UILabel *titleL = [[UILabel alloc]init];
        titleL.text = [self getLengthWithStr:model.title andLong:10];
        titleL.textColor = [UIColor colorWithHexString:@"#000000"];
        titleL.font = [UIFont systemFontOfSize:12];
        [view addSubview:titleL];
        titleL.makeCons(^{
            make.left.constants(10);
            make.top.view(imageView).bottom.constants(2);
        });
        
        UILabel *contenL = [[UILabel alloc]init];
        contenL.text = [self getLengthWithStr:model.content andLong:14];
        contenL.numberOfLines = 0;
        contenL.textColor = [UIColor colorWithHexString:@"#000000"];
        contenL.font = [UIFont systemFontOfSize:14];
        [view addSubview:contenL];
        contenL.makeCons(^{
            make.left.constants(10);
            make.top.view(titleL).bottom.constants(2);
        });

    }
    
}

- (void)initArrowView{
    self.scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, kScreenW, kScreenH)];
    self.scrollView.contentSize = CGSizeMake(150*4, 165);
    self.scrollView.directionalLockEnabled = YES;
    NSInteger  checkALLNum = [[[NSUserDefaults standardUserDefaults] objectForKey:KCheckAllNumKey] integerValue];//打卡次数
  

    for (int i = 0; i<4; i++) {
        UIImageView *imageView = [[UIImageView alloc] init];
        imageView.image = [UIImage imageNamed:@"icon_home_reward1"];
        
        [self.scrollView addSubview:imageView];
        imageView.makeCons(^{
            make.left.constants(150*i);
            make.width.constants(140);
            make.height.constants(165);
            make.top.constants(0);
        });
        
        UIImageView *selectIcon = [[UIImageView alloc] init];
        selectIcon.image = [UIImage imageNamed:@"icon_image_select"];
        [imageView addSubview:selectIcon];
        selectIcon.hidden = YES;
        selectIcon.makeCons(^{
            make.right.constants(-10);
            make.bottom.constants(-30);
            make.height.width.constants(40);
        });
        if (i==0) {
            self.selectIcon1 = selectIcon;
            if (checkALLNum>=1) {
                self.selectIcon1.hidden = NO;
            }
        }else if (i==1){
            self.selectIcon2 = selectIcon;
            if (checkALLNum>=2) {
                self.selectIcon2.hidden = NO;
            }
        }else if (i==2){
            self.selectIcon3 = selectIcon;
            if (checkALLNum>=3) {
                self.selectIcon3.hidden = NO;
            }
        }else if (i==3){
            self.selectIcon4 = selectIcon;
            if (checkALLNum>=4) {
                self.selectIcon4.hidden = NO;
            }

        }
        
    }
    [self.scrollViewBgView addSubview:self.scrollView];
    

}


-(NSString *)getLengthWithStr:(NSString *)str andLong:(NSInteger)count{
    NSString *backStr = str;
    if(str.length>count){
       NSString * nameStr = [str substringToIndex:count];
        backStr = [NSString stringWithFormat:@"%@...",nameStr];
    }
    
    return backStr;
}
- (void)getData{
    
    
    [self.anchorListScrollView removeAllSubviews];
    //获取个人信息接口
    [[BJNetManager shareNetManager] getGetUserInfoWithUserId:[[BJUserManager sharedManager] getUserId] completionHandler:^(BJGetUserInfoModel * _Nonnull model, NSError * _Nonnull error) {
        if (!error && [model.code intValue] == 0){
            [BJUserManager sharedManager].userInfoData = model.data;
        }
    }];

    //获取主播列表接口
    NSArray *dataQueryList = [[BJFMDBManager sharedManager] queryAllData];
    if (dataQueryList.count>0) {
        self.dataList = [dataQueryList mutableCopy];
        [self initUI];
    }else{
        NSDictionary *parm = @{
            @"isPageMode":@(YES),
            @"isRemoteImageUrl":@(YES),
            @"category":@"Popular",
            @"tag":@"All",
            @"limit":@(20),
            @"page":@(1)
        };

        [ASHUD showASLoading];

        [[BJNetManager shareNetManager] postSearchAnchorWallWithParm:parm completionHandler:^(BJAnchorWallModel * _Nonnull model, NSError * _Nonnull error) {
            [ASHUD hideHUD];

            dispatch_queue_t queue = dispatch_queue_create("queue", DISPATCH_QUEUE_CONCURRENT);
            dispatch_async(queue, ^{
                //文章列表
                for (int i = 0; i<model.data.count; i++) {
                    if (i==12) {
                        return;
                    }
                    model.data[i].title = self.titileArr[i];
                    model.data[i].content = self.contentArr[i];
                    model.data[i].imageArrStr = [self.imageArr[i] componentsJoinedByString:@","];
                    [self.dataList addObject:model.data[i]];
                    [[BJFMDBManager sharedManager] insertWitModel:model.data[i]];
                }
                
            });
            dispatch_barrier_async(queue, ^{
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self initUI];
                });
            });
            [[BJNetManager shareNetManager] getShortLinkMediaSearchWithCompletionHandler:^(BJVodeoListModel * _Nonnull item, NSError * _Nonnull error) {
                
                //视频列表
                for (int i = 0; i<item.data.count; i++) {
                    BJVodeoListDataModel * itemModel = item.data[i];
                    
                    model.data[i].title = self.titileArr[i];
                    model.data[i].content = self.contentArr[i];
                    model.data[i].anchorUrl = itemModel.middleThumbUrl;
                    model.data[i].playurl = itemModel.mediaUrl;
                    [[BJFMDBVoiceManager sharedManager] insertWitModel:model.data[i]];
                }

            }];
        }];
    }

}


- (IBAction)clickChickBtn:(id)sender {
    NSString * todayDateStr = [[NSUserDefaults standardUserDefaults] objectForKey:kTodayDateKey];
    if (![todayDateStr isEqualToString:[self getDate]]) {
        BJRewardPopView *rewardPopView = [[BJRewardPopView alloc]initWithTitle:@"Congratulations" andContent:@"Congratulations on getting an arrow, go use it now"];
        [rewardPopView showView];
        self.checkNum ++;
        [[NSUserDefaults standardUserDefaults] setInteger:self.checkNum forKey:KCheckNumKey];//
        [[NSUserDefaults standardUserDefaults] setInteger:1 forKey:KCheckAllNumKey];//打卡次数

        

        if (self.checkNum>=1) {
            self.selectIcon1.hidden = NO;
        }
        if (self.checkNum>=2) {
            self.selectIcon2.hidden = NO;
        }
        if (self.checkNum>=3) {
            self.selectIcon3.hidden = NO;
        }
        if (self.checkNum>=4) {
            self.selectIcon4.hidden = NO;
        }
    }else{
        BJRewardAginPopView *rewardAginPopView = [[BJRewardAginPopView alloc]initWithTitle:@"Mistake" andContent:@"I've checked in today, please come back tomorrow"];
        [rewardAginPopView showView];
        
    }


}

- (IBAction)clickMoreBtn:(id)sender {
    
    BJArticleViewController *view = [[BJArticleViewController alloc]init];
    [self.navigationController pushViewController:view animated:YES];

}

- (NSString *)getDate{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
     
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDate *currentDate = [NSDate date];
    NSString *dateString = [dateFormatter stringFromDate:currentDate];
    return dateString;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
